<template>
  <div>
    <!-- 页头 -->
    <NavBar />
    <div class="reservation-container">
      <div class="hero-banner">
        <h2>预约服务</h2>
        <p>为您的爱宠提供专业的美容、医疗、训练和寄养服务</p>
      </div>
      
      <!-- 选择服务大类 -->
      <div class="category-section">
        <h3 class="section-title">选择服务类型</h3>
        <div class="category-list">
          <button
            v-for="cat in categories"
            :key="cat.key"
            :class="['category-btn', { active: selectedCategory === cat.key }]"
            @click="selectCategory(cat.key)"
          >
            {{ cat.name }}
          </button>
        </div>
      </div>
      
      <!-- 选择服务项目（多选） -->
      <div v-if="selectedCategory" class="service-section">
        <h3 class="section-title">选择服务项目</h3>
        <div class="service-list">
          <div
            v-for="srv in currentServices"
            :key="srv.key"
            :class="['service-card', { selected: selectedService.includes(srv.key) }]"
            @click="toggleService(srv)"
          >
            <div class="service-title">{{ srv.name }}</div>
            <div class="service-desc">{{ srv.desc }}</div>
            <div class="service-price">￥{{ srv.price }}</div>
          </div>
        </div>
      </div>
      
      <!-- 选择日期（完整日历） -->
      <div v-if="selectedService.length" class="datetime-section">
        <h3 class="section-title">选择日期</h3>
        <div class="calendar">
          <div class="calendar-header">
            <button class="calendar-arrow" @click="prevMonth">&lt;</button>
            <span>{{ calendarYear }} 年 {{ calendarMonth + 1 }} 月</span>
            <button class="calendar-arrow" @click="nextMonth">&gt;</button>
          </div>
          <div class="calendar-body">
            <div class="calendar-row calendar-weekdays">
              <span v-for="d in weekDays" :key="d">{{ d }}</span>
            </div>
            <div v-for="(row, rowIdx) in calendarRows" :key="rowIdx" class="calendar-row">
              <span
                v-for="cell in row"
                :key="cell.dateStr"
                :class="['calendar-cell',
                  { today: cell.isToday, selected: cell.isSelected, disabled: cell.isDisabled }]
                "
                @click="selectDate(cell)"
              >
                {{ cell.day || '' }}
              </span>
            </div>
          </div>
        </div>
        
        <h3 class="section-title">选择时间</h3>
        <div class="time-select">
          <button 
            v-for="t in timeOptions" 
            :key="t" 
            :class="['time-btn', { 
              active: selectedTime === t, 
              disabled: isTimeDisabled(t) 
            }]"
            @click="!isTimeDisabled(t) && (selectedTime = t)"
          >
            {{ t }}
          </button>
        </div>
      </div>
      
      <!-- 备注 -->
      <div v-if="selectedService.length" class="remark-section">
        <h3 class="section-title">备注</h3>
        <textarea v-model="remark" placeholder="请输入备注（可选）"></textarea>
      </div>
      
      <!-- 总价和预约按钮 -->
      <div v-if="selectedService.length" class="summary-section">
        <div class="total-price">总计：<span>￥{{ selectedPrice }}</span></div>
        <button class="btn" @click="submitReservation">立即预约</button>
      </div>
    </div>
    
    <!-- 模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="hideModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>预约成功！</h2>
          <div class="success-icon">✓</div>
        </div>
        <div class="modal-body">
          <p>服务类型：{{ modalData.categoryName }}</p>
          <p>服务项目：{{ modalData.serviceNames }}</p>
          <p>日期：{{ modalData.date }}</p>
          <p>时间：{{ modalData.time }}</p>
          <p>备注：{{ modalData.remark || '无' }}</p>
          <p class="price-info">总价：￥{{ modalData.totalPrice }}</p>
        </div>
        <button class="close-btn" @click="hideModal">关闭</button>
      </div>
    </div>
    
    <!-- 页脚 -->
    <PageFooter />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import NavBar from '@/components/NavBar.vue';
import PageFooter from '@/components/PageFooter.vue';

// 服务大类
const categories = [
  { key: 'grooming', name: '宠物美容' },
  { key: 'medical', name: '宠物医疗' },
  { key: 'training', name: '宠物训练' },
  { key: 'boarding', name: '宠物寄养' },
];

// 各大类下的服务项目（通用结构，后续可扩展）
const servicesMap = {
  grooming: [
    { key: 'grooming1', name: '洗护护理', desc: '专业洗护护理服务', price: 188 },
    { key: 'grooming2', name: '美容造型', desc: '宠物美容造型设计', price: 268 },
    { key: 'grooming3', name: '健康体检', desc: '宠物健康体检套餐', price: 388 },
    { key: 'grooming4', name: '深度护理', desc: '深层皮毛护理', price: 288 },
  ],
  medical: [
    { key: 'medical1', name: '常规体检', desc: '基础健康检查', price: 200 },
    { key: 'medical2', name: '疫苗接种', desc: '宠物疫苗服务', price: 150 },
    { key: 'medical3', name: '疾病诊疗', desc: '常见疾病诊疗', price: 300 },
    { key: 'medical4', name: '手术治疗', desc: '宠物手术服务', price: 800 },
  ],
  training: [
    { key: 'training1', name: '基础服从', desc: '基础行为训练', price: 180 },
    { key: 'training2', name: '技能训练', desc: '专项技能训练', price: 260 },
    { key: 'training3', name: '行为矫正', desc: '不良行为矫正', price: 320 },
    { key: 'training4', name: '社交训练', desc: '社交能力提升', price: 220 },
  ],
  boarding: [
    { key: 'boarding1', name: '标准寄养', desc: '基础寄养服务', price: 100 },
    { key: 'boarding2', name: '豪华寄养', desc: '高端寄养环境', price: 200 },
    { key: 'boarding3', name: '医疗寄养', desc: '带医疗护理寄养', price: 300 },
    { key: 'boarding4', name: '特殊寄养', desc: '特殊需求寄养', price: 400 },
  ],
};

const selectedCategory = ref('');
const selectedService = ref([]); // 多选
const selectedTime = ref('09:00');
const remark = ref('');

// 日历相关
const today = new Date();
const calendarYear = ref(today.getFullYear());
const calendarMonth = ref(today.getMonth()); // 0-11
const selectedDate = ref(formatDate(today));

function formatDate(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

const calendarRows = computed(() => {
  const year = calendarYear.value;
  const month = calendarMonth.value;
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const daysInMonth = lastDay.getDate();
  const rows = [];
  let row = [];
  let dayOfWeek = firstDay.getDay();
  
  // 填充月初空白
  for (let i = 0; i < dayOfWeek; i++) {
    row.push({ day: '', dateStr: '', isToday: false, isSelected: false, isDisabled: true });
  }
  
  for (let d = 1; d <= daysInMonth; d++) {
    const dateObj = new Date(year, month, d);
    const dateStr = formatDate(dateObj);
    const isToday = dateStr === formatDate(today);
    const isSelected = dateStr === selectedDate.value;
    const isDisabled = dateObj < new Date(today.getFullYear(), today.getMonth(), today.getDate());
    
    row.push({
      day: d,
      dateStr,
      isToday,
      isSelected,
      isDisabled
    });
    
    if (row.length === 7) {
      rows.push(row);
      row = [];
    }
  }
  
  // 填充月末空白
  if (row.length) {
    while (row.length < 7) {
      row.push({ day: '', dateStr: '', isToday: false, isSelected: false, isDisabled: true });
    }
    rows.push(row);
  }
  
  return rows;
});

function prevMonth() {
  if (calendarMonth.value === 0) {
    calendarYear.value--;
    calendarMonth.value = 11;
  } else {
    calendarMonth.value--;
  }
}

function nextMonth() {
  if (calendarMonth.value === 11) {
    calendarYear.value++;
    calendarMonth.value = 0;
  } else {
    calendarMonth.value++;
  }
}

function selectDate(cell) {
  if (!cell.isDisabled && cell.day) {
    selectedDate.value = cell.dateStr;
  }
}

const timeOptions = [
  '09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00'
];

const currentServices = computed(() => {
  return selectedCategory.value ? servicesMap[selectedCategory.value] : [];
});

const selectedPrice = computed(() => {
  if (!selectedCategory.value || !selectedService.value.length) return 0;
  return selectedService.value
    .map(key => servicesMap[selectedCategory.value].find(s => s.key === key)?.price || 0)
    .reduce((a, b) => a + b, 0);
});

function selectCategory(key) {
  selectedCategory.value = key;
  selectedService.value = [];
}

function toggleService(srv) {
  const idx = selectedService.value.indexOf(srv.key);
  if (idx > -1) {
    selectedService.value.splice(idx, 1);
  } else {
    selectedService.value.push(srv.key);
  }
}

// 添加判断时间是否禁用的方法
function isTimeDisabled(time) {
  // 如果不是今天，则不禁用
  if (selectedDate.value !== formatDate(today)) return false;
  
  // 如果是今天，判断时间是否已过
  const [hours, minutes] = time.split(':').map(Number);
  const now = new Date();
  
  if (hours < now.getHours()) return true;
  if (hours === now.getHours() && minutes <= now.getMinutes()) return true;
  
  return false;
}

const showModal = ref(false);
const modalData = ref({
  categoryName: '',
  serviceNames: '',
  date: '',
  time: '',
  remark: '',
  totalPrice: 0,
});

function submitReservation() {
  if (isTimeDisabled(selectedTime.value)) {
    alert('请选择有效的预约时间！');
    return;
  }

  // 设置模态框的数据
  modalData.value.categoryName = categories.find(c => c.key === selectedCategory.value)?.name;
  modalData.value.serviceNames = selectedService.value.map(key => currentServices.value.find(s => s.key === key)?.name).join('、');
  modalData.value.date = selectedDate.value;
  modalData.value.time = selectedTime.value;
  modalData.value.remark = remark.value;
  modalData.value.totalPrice = selectedPrice.value;

  // 显示模态框
  showModal.value = true;
}

function hideModal() {
  showModal.value = false;

  // 清空备注字段
  remark.value = '';

  // 重置选中的服务、日期和时间
  selectedCategory.value = '';
  selectedService.value = [];
  selectedDate.value = formatDate(today);
  selectedTime.value = '09:00';
}
</script>

<style scoped>
.reservation-container {
  max-width: 1000px;
  margin: 40px auto;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.08);
  padding: 40px;
  overflow: hidden;
}

.hero-banner {
  position: relative;
  height: 200px;
  margin: -40px -40px 40px -40px;
  background-image: linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)), url('@/assets/reservation-banner.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.hero-banner h2 {
  font-size: 36px;
  margin-bottom: 10px;
}

.hero-banner p {
  font-size: 18px;
  opacity: 0.9;
}

.section-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  position: relative;
  padding-bottom: 10px;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50px;
  height: 3px;
  background-color: #e76f51;
  border-radius: 3px;
}

.category-section, .service-section, .datetime-section, .remark-section, .summary-section {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 16px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.category-section:hover, .service-section:hover, .datetime-section:hover, .remark-section:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.05);
}

.category-list {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 16px;
  flex-wrap: wrap;
}

.category-btn {
  background: #f4f4f4;
  border: none;
  border-radius: 12px;
  padding: 14px 28px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.category-btn.active, .category-btn:hover {
  background: #e76f51;
  color: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(231,111,81,0.15);
}

.service-list {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 16px;
}

.service-card {
  width: 220px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  padding: 24px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  position: relative;
}

.service-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(231,111,81,0.12);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.service-card:hover::before {
  opacity: 1;
}

.service-card.selected, .service-card:hover {
  border: 2px solid #e76f51;
  transform: translateY(-4px);
}

.service-title {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 10px;
  color: #333;
}

.service-desc {
  font-size: 15px;
  color: #666;
  margin-bottom: 16px;
  min-height: 45px;
}

.service-price {
  color: #e76f51;
  font-weight: bold;
  font-size: 18px;
}

/* 日历样式 */
.calendar {
  margin: 16px 0 24px 0;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.05);
  padding: 24px;
  transition: box-shadow 0.3s ease;
}

.calendar:hover {
  box-shadow: 0 6px 20px rgba(0,0,0,0.08);
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 16px;
  gap: 24px;
}

.calendar-arrow {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #e76f51;
  padding: 0 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.calendar-arrow:hover {
  background: #fbe8dc;
  transform: scale(1.1);
}

.calendar-body {
  width: 100%;
}

.calendar-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.calendar-weekdays {
  color: #aaa;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
}

.calendar-cell {
  width: 42px;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 16px;
  cursor: pointer;
  margin: 1px;
  transition: all 0.3s ease;
}

.calendar-cell.today {
  border: 2px solid #e76f51;
  font-weight: bold;
}

.calendar-cell.selected {
  background: #e76f51;
  color: #fff;
  font-weight: bold;
  transform: scale(1.05);
}

.calendar-cell:not(.disabled):hover:not(.selected):not(.today) {
  background: #fbe8dc;
  transform: scale(1.05);
}

.calendar-cell.disabled {
  color: #ccc;
  background: #f4f4f4;
  cursor: not-allowed;
  opacity: 0.7;
}

.datetime-section select {
  margin-top: 8px;
  padding: 10px 16px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 16px;
  margin-right: 16px;
  transition: border-color 0.3s ease;
}

.datetime-section select:hover {
  border-color: #e76f51;
}

.remark-section textarea {
  width: 100%;
  min-height: 80px;
  border-radius: 10px;
  border: 1px solid #ddd;
  padding: 14px;
  font-size: 16px;
  margin-top: 8px;
  resize: vertical;
  transition: border-color 0.3s ease;
}

.remark-section textarea:hover {
  border-color: #e76f51;
}

.remark-section textarea:focus {
  outline: none;
  border-color: #e76f51;
  box-shadow: 0 0 0 3px rgba(231,111,81,0.15);
}

.summary-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 32px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.total-price {
  font-size: 24px;
  color: #e76f51;
  font-weight: bold;
}

.btn {
  background-color: #e76f51;
  color: white;
  padding: 16px 40px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 600;
  font-size: 18px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(231,111,81,0.15);
}

.btn:hover {
  background-color: #d65c41;
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(231,111,81,0.2);
}

.btn:active {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(231,111,81,0.2);
}

/* 时间选择按钮组 */
.time-select {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
  width: 100%;
}

.time-btn {
  flex: 1;
  min-width: 100px;
  padding: 14px 8px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.03);
}

.time-btn:hover:not(.disabled) {
  border-color: #e76f51;
  transform: translateY(-2px);
}

.time-btn.active {
  background: #e76f51;
  color: white;
  border-color: #e76f51;
  font-weight: 600;
  transform: translateY(-2px);
}

.time-btn.disabled {
  background: #f4f4f4;
  color: #bbb;
  cursor: not-allowed;
  opacity: 0.7;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  backdrop-filter: blur(2px);
  transition: opacity 0.3s ease;
}

.modal-content {
  background: white;
  padding: 32px;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  max-width: 480px;
  width: 90%;
  text-align: center;
  transform: scale(0.95);
  transition: transform 0.3s ease;
  position: relative;
}

.modal-overlay.active .modal-content {
  transform: scale(1);
}

.modal-header {
  margin-bottom: 24px;
}

.modal-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 12px;
}

.success-icon {
  display: inline-block;
  width: 48px;
  height: 48px;
  background: #e76f51;
  color: white;
  border-radius: 50%;
  font-size: 24px;
  line-height: 48px;
  margin-bottom: 16px;
  animation: successAnimation 0.5s ease;
}

@keyframes successAnimation {
  0% { transform: scale(0); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.modal-body p {
  margin: 12px 0;
  font-size: 16px;
  color: #666;
}

.price-info {
  font-size: 20px;
  font-weight: bold;
  color: #e76f51;
  margin-top: 16px;
}

.close-btn {
  background-color: #e76f51;
  color: white;
  padding: 14px 32px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  margin-top: 24px;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(231,111,81,0.15);
}

.close-btn:hover {
  background-color: #d65c41;
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(231,111,81,0.2);
}
</style>